#include "common_lib/socket_client_interface.h"

using namespace Socket;

SocketClientInterface::SocketClientInterface(const std::string ip, const unsigned short port)
: m_ios_executors_{boost::make_shared<boost::asio::io_service>()},
  m_ios_work_acceptors_(boost::make_shared<boost::asio::io_service::work>(*m_ios_executors_)),
  server_ip_(ip),
  server_port_(port)
{
    printf("starting %s, %d\n", ip.c_str(), port);

    boost::asio::ip::tcp::resolver resolve(*m_ios_executors_);
    endpoints_ = resolve.resolve(ip, std::to_string(port));
    ptr_session_ = (boost::make_shared<SocketSession>(m_ios_executors_, endpoints_, this));
}

SocketClientInterface::~SocketClientInterface()
{
    if (!m_ios_executors_->stopped())
    {
        m_ios_executors_->stop();
        // m_executors_thread_group_.interrupt_all();
        // m_executors_thread_group_.join_all();
    }
}

void SocketClientInterface::AsyncConnect()
{
    ptr_session_->StartConnect(endpoints_.begin());
}

void SocketClientInterface::StartRead()
{
    ptr_session_->StartRead();
}

void SocketClientInterface::Stop()
{

}

void SocketClientInterface::Start()
{
    AsyncConnect();
    // StartRead();
    // ptr_session_->StartWrite();
    boost::system::error_code ec;
    m_ios_executors_->run(ec);
}